package com.example.lockLearning;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Lock2 {

    private final Lock lock = new ReentrantLock();

    /**
     * `tryLock()` 方法允许线程尝试获取锁而不阻塞。
     * 1. `tryLock()` 尝试获取锁，获取不到立即返回 `false`。
     * 2. 避免线程一直等待锁，防止死锁。
     */
    public void tryIncrement() {
        if (lock.tryLock()) {
            try {
                for (int i = 0; i < 5; i++) {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                }
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "failed to get lock");
        }
    }

    public static void main(String[] args) {

        Lock2 lock2 = new Lock2();

        Thread t1 = new Thread(lock2::tryIncrement);
        Thread t2 = new Thread(lock2::tryIncrement);

        t1.start();
        t2.start();

    }
}
